package com.syx.security.Interceptor;

import cn.hutool.core.util.StrUtil;
import com.syx.commoncore.Constant.Constant;
import com.syx.commoncore.Constant.HttpConstants;
import com.syx.commoncore.Utils.ThreadLocalUtil;
import com.syx.security.Service.TokenService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    //到时候配置到哪个容器哪个容器就进行管理
    @Value("${jwt.secret}")
    private String secret;

    @Resource
    TokenService tokenService;


    //在发送给拦截器前就可以进行延长
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=getToken(request);
        //第一次登录的时候是没有jwt令牌的先放行
        if (token==null){
            return true;
        }
        Long userId = tokenService.getUserIdFromToken(token,secret);
        String userKey = tokenService.getUserKeyFromToken(token,secret);
        String tokenKey = tokenService.getTokenKey(userKey);
        ThreadLocalUtil.set(Constant.USER_ID, userId);
        ThreadLocalUtil.set(Constant.USER_TOKEN_KEY, tokenKey);


        //延长token的时间，如果小于180分钟就进行延长。
        tokenService.extendToken(token,secret);
        //放行
        //在这边每次都进行判断status是否是1，如果是0拉黑1正常

        return true;


    }

    @Override
    public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex) throws Exception{
        ThreadLocalUtil.remove();


    }

    public String getToken(HttpServletRequest request){

        String token=request.getHeader(HttpConstants.AUTHENTICATION);
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)){
            token=token.replaceFirst(HttpConstants.PREFIX,"");

        }
        return token;

    }


}
